<?php

namespace app\console\command;

use app\common\model\Vod;
use Aws\AwsService;
use CloudFlare\CloudFlareApiClient;
use HuaweiVod\HuaweiVod;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Log;

class ClearCloudflareVod extends Command
{
    protected function configure()
    {
        $this->setName('clear_cloudflare_vod')
            ->setDescription('clear no use vod list');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->info("execute list cloudflare videos");
        try {
            $this->getVideoList($output);
        } catch (\Exception $exception) {
            Log::error($exception->getMessage());
            Log::error($exception->getTraceAsString());
//            $output->error($exception->getMessage());
        }
    }

    protected function getVideoList($output)
    {
        $cfClient = new CloudFlareApiClient();

        $deleteCount = 0;
        for ($day = 19; $day < 23; $day++) { // 清理7-19 到7-23上传的视频
            for ($i = 0; $i < 24; $i++) { // 一次只能返回1000条,所以每隔一小时轮询
                $start = '2024-07-' . sprintf('%02d', $day) . 'T' . sprintf("%02d", $i) . ':00:00Z';
                $end = '2024-07-' . sprintf('%02d', $day) . 'T' . sprintf("%02d", $i) . ':59:59Z';
                $output->info('begin to get video list:' . $start . ' to ' . $end);
                $result = $cfClient->getVideoList($start, $end);
                if (!empty($result['result']['videos']) && count($result['result']['videos']) > 0) {
                    $videoList = $result['result']['videos'];
                    foreach ($videoList as $video) {
                        $vod = Db::name('vod')
                            ->where('platform', '=', 'cloudflare')
                            ->where('asset_id', '=', $video['uid'])
                            ->find();
                        if (!$vod) {
//                            Log::info('delete video:' . json_encode($video));
                            $cfClient->deleteVideo($video['uid']);
                            $deleteCount++;
                        } else {
//                            Log::info('no need to delete video:' . $video['uid']);
                        }
                    }
                }
            }
        }

        $output->info('delete count:' . $deleteCount);
    }
}
